package com.blue.core.auth;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.blue.core.util.NumberUtil;


/**
 * 消息摘要算法，封装了MD5和SHA-1两种算法
 * 
 * @author zhengj
 * @since 1.0
 * @date 2008-12-22
 */
public class DigestUtil
{
	private DigestUtil()
	{
	}

	/**
	 * 用md5算法加密，返回16进制小写字母
	 * 
	 * @param src 密码原文
	 * @return md5信息摘要
	 */
	public static String md5Hex(String src)
	{
		String msg = null;
		if (src == null || src.isEmpty())
			return msg;

		try
		{
			byte[] dest = src.getBytes("utf-8");
			MessageDigest md5 = MessageDigest.getInstance("md5");
			msg = NumberUtil.toHexString(md5.digest(dest));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}
		return msg;
	}
	
	/**
	 * 用MD5算法加密，返回字节数组
	 * 
	 * @param src 密码原文
	 * @return md5信息摘要，返回字节数组
	 */
	public static byte[] md5(String src)
	{
		byte[] bytes = null;
		if (src == null || src.isEmpty())
			return bytes;

		try
		{
			byte[] dest = src.getBytes("utf-8");
			MessageDigest md5 = MessageDigest.getInstance("md5");
			bytes = md5.digest(dest);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return bytes;
	}

	/**
	 * 用SHA-1算法加密，返回16进制小写字母
	 * 
	 * @param src 密码原文
	 * @return SHA-1信息摘要
	 */
	public static String sha1Hex(String src)
	{
		String msg = null;
		if (src == null || src.isEmpty())
			return msg;

		try
		{
			byte[] dest = src.getBytes("utf-8");
			MessageDigest sha1 = MessageDigest.getInstance("sha1");
			msg = NumberUtil.toHexString(sha1.digest(dest));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 用SHA-1算法加密，返回字节数组
	 *
	 * @param src 密码原文
	 * @return SHA-1信息摘要
	 */
	public static byte[] sha1(String src)
	{
		byte[] bytes = null;
		if (src == null || src.isEmpty())
			return bytes;

		try
		{
			byte[] dest = src.getBytes("utf-8");
			MessageDigest sha1 = MessageDigest.getInstance("sha1");
			bytes = sha1.digest(dest);
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}
		return bytes;
	}

	/**
	 * 用MD5算法比较密码原文与密文是否相等
	 * 
	 * @param src 密码原文
	 * @param md MD5信息摘要
	 * @return 相等返回true，否则返回false
	 */
	public static boolean equalMd5(String src, String md)
	{
		if (src == null || md == null)
			return false;
		return md.equals(md5Hex(src));
	}

	/**
	 * 用SHA-1算法比较密码原文与密文是否相等
	 * 
	 * @param src 密码原文
	 * @param md SHA-1信息摘要
	 * @return 相等返回true，否则返回false
	 */
	public static boolean equalSha1(String src, String md)
	{
		if (src == null || md == null)
			return false;
		return md.equals(sha1Hex(src));
	}
}
